#!/usr/bin/python
import wx, threading, time, sys, chatclient, Queue, client, socket

class MyMenuBar(wx.MenuBar):
	def __init__(self, *args, **kwds):
		# begin wxGlade: MyMenuBar.__init__
		wx.MenuBar.__init__(self, *args, **kwds)
		self.File = wx.Menu()
		self.Connect = wx.MenuItem(self.File, 1, "Connect", "Connect to the game server", wx.ITEM_NORMAL)
		self.Quit = wx.MenuItem(self.File, 2, "Quit", "", wx.ITEM_NORMAL)
		self.Chat = wx.Menu()
		self.chatConnect = wx.MenuItem(self.File, 3, "Connect", "Connect to the chatting server", wx.ITEM_NORMAL)
		self.Chat.AppendItem(self.chatConnect)
		self.File.AppendItem(self.Connect)
		self.File.AppendItem(self.Quit)
		self.Append(self.File, "File")
		self.Append(self.Chat, "Chat")
		self.__set_properties()
		self.__do_layout()

	def __set_properties(self):
		pass

	def __do_layout(self):
		pass

class Frame(wx.Frame):
	def __init__(self, name):
		self.name = name
		wx.Frame.__init__(self, None, -1, "Rung", (-1,-1), (800,600), wx.DEFAULT_FRAME_STYLE ^ (wx.RESIZE_BORDER | wx.MINIMIZE_BOX |wx.MAXIMIZE_BOX))
		self.Center()
		self.qIn = Queue.Queue()
		self.qOut = Queue.Queue()
		self.qMove = Queue.Queue()
		self.qStatus = Queue.Queue()
		self.qChatIn = Queue.Queue()
		self.qChatOut = Queue.Queue()
		self.moveImage = [(0, None), (1, None), (2, None), (3, None)]
		self.image = []
		self.hand = []
		self.chatFrame = None
		self.input = False
		self.statusText = "status"
		self.team0Score = "00"
		self.team1Score = "00"
		self.rung = ""
		self._newMove()
		self.client = client.Client(name, self.qOut, self.qIn, self.qMove, self.qStatus)
		self.playerNum = None
		menuBar = MyMenuBar()
		self.SetMenuBar(menuBar)
		self.Bind(wx.EVT_MENU, self._OnMenu)
		self.timer = wx.Timer(self)
		self.Bind(wx.EVT_TIMER, self._getInput, self.timer)
		self.timer.Start(200)
		self.clientThread = threading.Thread(target=self.client.connect)
		self.clientThread.daemon = True
		#self.clientThread.start()
		self.chatThread = threading.Thread(target=chatclient.recvChat, args=(self.name, self.qChatOut, self.qChatIn))
		self.chatThread.daemon = True
	
	def _resetGUI(self):
		self.hand = []
		self._newMove()
		self._initHand()
		self._initMove()
		self._initGUI()
	
	def _newMove(self):
		self.moves = []
		self.moves.append((0, None))
		self.moves.append((1, None))
		self.moves.append((2, None))
		self.moves.append((3, None))
		
	def _initHand(self):
		self.image = []
		for card in self.hand:
			self.image.append((card, wx.Image('../Cards/'+card+'.png', wx.BITMAP_TYPE_PNG)))
	
	def _initMove(self):
		self.moveImage = [(0, None), (1, None), (2, None), (3, None)]
		for player, card in self.moves:
			if(card != None):
				self.moveImage[player] = (player, wx.Image('../Cards/'+card+'.png', wx.BITMAP_TYPE_PNG))
		
	def _initGUI(self):
		self.DestroyChildren()
		self.cardImg = {}
		posi = 274
		self.id = 0
		for card, img in self.image:
			temp = img.ConvertToBitmap()
			if(len(self.image)-1 == self.id):
				bmp = wx.StaticBitmap(self, -1, temp, (posi, 450), (temp.GetWidth(), temp.GetHeight()))
			else:
				bmp = wx.StaticBitmap(self, -1, temp, (posi, 450), (15, temp.GetHeight()))
			bmp.Bind(wx.EVT_LEFT_DOWN, self._OnLeftDown, bmp, bmp.SetId(self.id))
			self.cardImg[bmp.GetId()] = card
			self.id += 1
			posi += 15
		for player, img in self.moveImage:
			if(img == None): pass
			else:
				temp = img.ConvertToBitmap()
				ownPlayerNum = self.playerNum
				if(ownPlayerNum == 3):
					ownPlayerNum = -1
				if(player-ownPlayerNum == 1 or player-ownPlayerNum == -3):
					#left card 
					bmp = wx.StaticBitmap(self, -1, temp, (280, 200), (temp.GetWidth(), temp.GetHeight()))
				elif(player-ownPlayerNum == 2 or player-ownPlayerNum == -2):
					#top card
					bmp = wx.StaticBitmap(self, -1, temp, (369, 100), (temp.GetWidth(), temp.GetHeight()))
				elif(player-ownPlayerNum == 3 or player-ownPlayerNum == -1):
					#right card
					bmp = wx.StaticBitmap(self, -1, temp, (455, 200), (temp.GetWidth(), temp.GetHeight()))
				elif(player-ownPlayerNum == 4 or player-ownPlayerNum == 0):
					#bottom car
					bmp = wx.StaticBitmap(self, -1, temp, (369, 300), (temp.GetWidth(), temp.GetHeight()))
		if(self.playerNum != None):
			wx.StaticText(self, -1, "player " + str((self.playerNum+2)%4), (369, 80))		#top
			wx.StaticText(self, -1, "player " + str((self.playerNum+1)%4), (280, 180))		#left
			wx.StaticText(self, -1, "player " + str((self.playerNum+3)%4), (475, 180))		#right
			wx.StaticText(self, -1, "player " + str(self.playerNum)+"(you)", (369, 400))		#self	
		wx.TextCtrl(self, -1, self.statusText, pos=(10, 10), size=(400, 30))
		score = "Score:\n team1 = " + self.team0Score + "\n team2 = " + self.team1Score + "\nRung: " + self.rung
		wx.StaticText(self, -1, score, (10, 60))
		
		
		
	def _getInput(self, evt):
		while(self.qIn.qsize()):
			msg = self.qIn.get(0)
			if(msg == "i"):
				self.input = True
			elif(msg == "r"):
				self._resetGUI()
			elif(msg != ""):
				clist = msg.split(":")
				self.hand = []
				for card in clist:
					self.hand.append(card)
				self._initHand()
				self._initGUI()
			else:
				self._resetGUI()
		while(self.qMove.qsize()):
			msg = self.qMove.get(0)
			if(msg[0] == "p"):
				if(self.playerNum == None):
					self.playerNum = int(msg[1])
				else:
					pass
			elif(msg[0] == "n"):
				self._newMove()
				self._initMove()
				self._initGUI()
			else:
				self.moves[int(msg[0])] = (int(msg[0]),msg[1:])
				self._initMove()
				self._initGUI()
		while(self.qStatus.qsize()):
			msg = self.qStatus.get(0)
			amsg = msg[1:]
			if(msg[0] == "s"):
				self.statusText = amsg
			elif(msg[0] == "r"):
				self.rung = amsg
			elif(msg[0] == "t"):
				#print amsg
				slist = amsg.split(":")
				self.team0Score = slist[0]
				self.team1Score = slist[1]
			elif(msg[0] == "d"):
				dlg = wx.MessageDialog( self, "Team " + msg[1] + " won the game", "Winner", wx.OK)
				dlg.ShowModal()
				dlg.Destroy()
				self.qOut.put("ok")
			elif(msg[0] == "c"):
				seatLst = amsg.split(":")
				aSeatList = []
				ctr = 1
				print amsg
				print seatLst
				for s in seatLst:
					if(s == "1"):
						aSeatList.append("Seat " + str(ctr))
					ctr += 1
				print(aSeatList)
				dlg = wx.SingleChoiceDialog(self, "Select seat", "Seat", aSeatList)
				dlg.ShowModal()
				sel = dlg.GetSelection()
				seatSel = aSeatList[sel][5]
				print("seat selected: " + seatSel)
				self.qOut.put(seatSel)
			
			self._initGUI()
			#print msg
			
	def _OnLeftDown(self, evt):
		if(self.input):
			id = evt.GetId()
			#print self.cardImg[id]
			self.qOut.put(id)
			self.input = False
			
	def _OnMenu(self, evt):
		id = evt.GetId()
		if(id == 1):
			if(not self.clientThread.isAlive()):
				dlg = wx.TextEntryDialog( self, "Enter your nick(3 characters)", "Name", "LUN")
				dlg.ShowModal()
				name = dlg.GetValue()
				self.client.name = name
				self.clientThread.start()
		elif(id == 2):
			print "quit"
			if(self.chatFrame):
				self.chatFrame.Destroy()
			self.Destroy()
		elif(id == 3):
			if(self.chatFrame == None):
				self.chatFrame = chatclient.MyGUI(self.qChatIn, self.qChatOut)
				self.chatFrame.Show()
				self.chatThread.start()			

if __name__ == '__main__':
	'''if(len(sys.argv) < 2):
		print("usage: python client.py [username]")
	elif(len(sys.argv[1]) != 3):
		print("username should be 3 letters") 
	else:
	name = sys.argv[1]'''
	app = wx.App()
	name = "gandu"
	frame = Frame(name)
	frame.Show()
	frame._initGUI()
	app.MainLoop()
